#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# mysql连接
#
# wencan
# 2019-04-15

import logging

import sqlalchemy
import sqlalchemy.orm

__all__ = ("MyDB",)

log = logging.getLogger(__name__)

class MyDB:
    def __init__(self, *args, **kwargs):
        self._args = args
        self._kwargs = kwargs
        self._connected = False
    
    def _connect(self) -> None:
        '''
        连接到数据库
        需要时再连接，会影响fork
        '''

        if self._connected:
            return

        self._engine = sqlalchemy.create_engine(*self._args, **self._kwargs)
        self._connected = True

        def ping():
            session_maker = sqlalchemy.orm.sessionmaker(bind=self._engine)
            session = session_maker()
            try:
                result = session.execute("SELECT NOW()")
                result.fetchone()

                session.commit()
            finally:
                session.close()

            log.info("mysql connected!")

        # 来一次ping操作
        # thread = Thread(target=ping, daemon=True)
        # thread.start()
        ping()

    def session_maker(self, expire_on_commit: bool=False) -> sqlalchemy.orm.sessionmaker:
        '''返回sessionmake'''

        self._connect()

        return sqlalchemy.orm.sessionmaker(bind=self._engine, expire_on_commit=expire_on_commit)
